﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Top.Base.Common;
using Top.Base.RedisKey;
using Top.Web;
using Top.Data;
using Top.PointStore.Business;
using Top.Web.Api;
using Top.Core;

namespace Top.PointStore.LuckTurntable
{
    public class LuckProductManager
    {
        private static Top.Common.TopCacheUtil cacheUtil = new Top.Common.TopCacheUtil();


        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static async Task<bool> Update(string dataList)
        {
            dataList = dataList.Trim();
            if (string.IsNullOrWhiteSpace(dataList))
            {
                return false;
            }

            List<LuckProduct> list = new List<LuckProduct>();
            string[] datalist_items = dataList.Split('|');
            for (int i = 0; i < datalist_items.Length; i++)
            {
                string[] items = datalist_items[i].Split(';');
                if (items.Length >= 4)
                {
                    list.Add(new LuckProduct()
                    {
                        ID = Convert.ToInt32(items[0]),
                        ProductKid = Convert.ToInt32(items[1]),
                        Name = items[2],
                        Count = Convert.ToInt32(items[3]),
                        Point = Convert.ToInt32(items[4]),
                        Chance = Convert.ToInt32(items[5]),                        
                        Rate = Convert.ToInt32(items[6]),
                        MaxCount = Convert.ToInt32(items[7]),
                        LuckCount = Convert.ToInt32(items[8]),
                        Description = items[9],
                        Angle = Convert.ToInt32(items[10])
                    });
                }
            }
            return await LuckTurntableManager_Plus.Update(list);
        }


        public static async Task<bool> Update(LuckProduct model)
        {
            using (var db = new DbTour())
            {
                const string sql = " update T_LuckProduct set Kid={0:ProductKid},Angle={0:Angle},Name={0:Name},Chance={0:Chance},Count={0:Count},Point={0:Point},Description={0:Description},Rate={0:Rate},MaxCount={0:MaxCount},LuckCount={0:LuckCount} where ID={0:ID}";
                return await db.Sql(sql, model).ExecuteNonQuery() > 0;
            }
        }

        /// <summary>
        /// 获取用户积分
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static async Task<T_PointMain_new> GetBrokerPoint(OAuthUser user)
        {
            if (user==null) return null;
            T_PointMain_new model = new T_PointMain_new();
            try
            {
                cacheUtil.TimeOut = 30;
                object pointObj = cacheUtil.GetObject(string.Format(BrokerKey.BrokerPointMain,user.UserToken));

                //string brokerDetail = await RedisProvider.StringGet(string.Format(BrokerKey.BrokerPointMain, userKid));
                //if (!string.IsNullOrEmpty(brokerDetail))
                if (pointObj != null)
                {
                    //model = Json.ToObject<T_PointMain>(brokerDetail);
                    model = pointObj as T_PointMain_new;
                }
                else
                {
                    using (var db = DataBase.Reader())
                    {
                        const string sql = @"select * from T_PointMain_new where F_UserToken = {0} limit 1";
                        T_PointMain_new resultModel = await db.Sql(sql, user.UserToken).FirstOrDefault<T_PointMain_new>();
                        if (resultModel != null)
                        {
                            model = resultModel;
                            cacheUtil.AddObject(string.Format(BrokerKey.BrokerPointMain, user.UserToken), resultModel);
                            //await RedisProvider.StringSet(string.Format(BrokerKey.BrokerPointMain, userKid), Json.ToJsonString(model));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(string.Format("Redis操作 类名[PointManager] 方法名[Get] 经纪人KID[{1}] 异常信息：{0}", ex.ToString(), user.UserToken));
            }
            return model;

        }


        public static int UpdateBrokerPoint(T_PointMain_new pointMain, OAuthUser user, int point, string remark)
        {
            if (pointMain == null) return -1;

            pointMain.F_PointBalance += point;
            //TODO 积分更新有问题 待确认
            if (point > 0)
            {
                pointMain.F_PointAll += point;
            }
            if (point < 0)
            {
                if (pointMain.F_PointBalance < -point)
                {
                    return -4; //无购买能力
                }

                pointMain.F_PointCash += -point;
            }
            return UpdateField(pointMain, user);
            //if (IsRecord && resultID > 0)//是否开启纪录明细
            //{
            //    await PointDetailManager.AddPoint(userKid, point, remark, db);
            //}
        }


        private static int UpdateField(T_PointMain_new pointMain,OAuthUser user)
        {
            if (pointMain==null) return -1;
            if (user==null) return -1;

            #region cache
            try
            {
                cacheUtil.AddObject(string.Format(BrokerKey.BrokerPointMain, user.UserToken), pointMain);
                return 1;
            }
            catch (Exception ex)
            {
                Trace.TraceError(string.Format("cache操作 类名[PointManager] 方法名[UpdateField] 经纪人KID[{1}] 异常信息：{0}", ex.ToString(), user.UserToken));
                return -1;
            }
            #endregion

            #region redis

            //try
            //{
            //    await RedisProvider.StringSet(string.Format(BrokerKey.BrokerPointMain, userKid), Json.ToJsonString(model));
            //    return 1;
            //}
            //catch (Exception ex)
            //{
            //    Trace.TraceError(string.Format("Redis操作 类名[PointManager] 方法名[UpdateField] 经纪人KID[{1}] 异常信息：{0}", ex.ToString(), userKid));
            //    return 0;
            //}

            #endregion

            #region sql

            //var obj = new
            //{
            //    F_PointBalance = pointBalance,
            //    F_PointCash = pointCash,
            //    F_UserKid = userKid,
            //    F_PointAll = pointAll
            //};
            //const string sql = @"update T_PointMain set F_PointBalance={0:F_PointBalance},F_PointCash={0:F_PointCash},F_PointAll={0:F_PointAll} where F_UserKid={0:F_UserKid}";
            //return await db.Sql(sql, obj).ExecuteNonQuery();

            #endregion

        }


        public static int Edit(int id, string productName, int productKid, int count, double chance, double point, string description)
        {
            int res = 0;
            using (var db = new DbTour())
            {
                const string sql = " update T_LuckProduct set Kid={1},Name={2},Chance={3},Count={4},Point={5},Description={6},MaxCount={4},LuckCount=0 where ID={0}";
                res = db.Sql(sql, id,productKid,productName,chance,count,point,description).ExecuteNonQuery().Result;
            }
            LuckBigWheel.InitRule().Wait();
            return res;
        }
        public static int Edit(int id, string productName, int productKid, int count, double chance, double point, string description, double thx)
        {
            int res = 0;
            using (var db = new DbTour())
            {
                const string sql = " update T_LuckProduct set Kid={1},Name={2},Chance={3},Count={4},Point={5},Description={6},MaxCount={4},LuckCount=0 where ID={0}";
                res = db.Sql(sql, id, productKid, productName, chance, count, point, description).ExecuteNonQuery().Result;
                string thxSQL = "update T_LuckProduct set Chance={0} where Kid=-1";
                db.Sql(thxSQL, thx).ExecuteNonQuery().Wait();
            }
            LuckBigWheel.InitRule().Wait();
            return res;
        }

        public static int Delete(int id)
        {
            int res = 0;
            using (var db = new DbTour())
            {
                const string sql = " update T_LuckProduct set Kid={1},Name={2},Chance={3},Count={4},Point={5},Description={6} where ID={0}";
                res = db.Sql(sql, id, 0,"", 0, 0, 0, "").ExecuteNonQuery().Result;
            }
            LuckBigWheel.InitRule().Wait();
            return res;
        }

        public static int Clear()
        {
            int res = 0;
            using (var db = new DbTour())
            {
                const string sql = " update T_LuckProduct set Kid={1},Name={2},Chance={3},Count={4},Point={5},Description={6} where 1={0}";
                res = db.Sql(sql,1, 0, "暂无奖品", 0, 0, 0, "").ExecuteNonQuery().Result;
            }
            LuckBigWheel.Init();
            Configs.AppSettings["BigTurnTableIsOpen"] = "0";
            return res;
        }
    }
}
